﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web.Mvc;
using DataAccess.Entities;
using Zeenck.DataAccess;
using Zeenck.DataAccess.Repositories;
using Zeenck.Models;

namespace Zeenck.Controllers
{
    public class HomeController : Controller
    {
        [Authorize]
        public ActionResult Index()
        {
            IRepository<Account> repo = new AccountRepository();
            List<Account> accounts = repo.GetAll().ToList();
            Profile p = (from a in accounts where a.UserName.Equals(User.Identity.Name) select a.Profile).FirstOrDefault();
            IRepository<Profile> profileRepo = new ProfileRepository();
            Debug.Assert(p != null, "p != null");
            Profile profile = profileRepo.GetById(p.Id);

            if (profile != null && profile.Complete)
            {
                ZeenckProfile zeenckProfile = ProfileModule.ConvertToZeenckProfile(profile);
                return View("Index", zeenckProfile);
            }

            Debug.Assert(profile != null, "profile != null");
            return Redirect(Url.CompleteRegistration(profile.Id));
        }

        public ActionResult About()
        {
            return View("About");
        }

        public ActionResult ContactUs()
        {
            return View("ContactUs");
        }

        public ActionResult Help()
        {
            return View("Help");
        }

        [HttpPost]
        public JsonResult FindInterests(string searchText, int maxResults)
        {
            IRepository<Interest> repository = new InterestRepository();
            var result = repository.Find(searchText, maxResults);
            return Json(result);
        }

        [HttpPost]
        [Authorize]
        public ActionResult AddInterest(string name)
        {
            IRepository<Interest> repo = new InterestRepository();
            Interest newInterest = repo.Find(name, 1).First();

            IRepository<Account> accountRepo = new AccountRepository();
            int profileId = accountRepo.GetAll()
                .Where(x => x.UserName == User.Identity.Name).ToList().First().Profile.Id;

            IRepository<Profile> profileRepo = new ProfileRepository();
            profileRepo.GetById(profileId).AddInterest(newInterest);

            return Json(new {status = true});
        }
    }
}
